<template>
  <div class="containerBG">
    <el-card class="boxCard ">
      <p class="Title">添加权限</p>
      <letterSearch :fun="getList" :zm.sync="zmValue"></letterSearch>
      <div class="box">
        <div class="boxLeft">
          <el-table
            :data="tableData"
            style="width: 100%;margin-bottom: 20px;"
            height="700"
            border
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-table :data="props.row.children" border>
                  <el-table-column
                    prop="action"
                    label="方法名"
                  ></el-table-column>
                  <el-table-column
                    prop="uri"
                    label="路由地址"
                  ></el-table-column>
                  <el-table-column
                    prop="method"
                    label="请求方式"
                    width="100px"
                  ></el-table-column>
                  <el-table-column label="操作" width="80px">
                    <template slot-scope="scope">
                      <el-button
                        type="primary"
                        size="mini"
                        @click="handleAdd(scope.row)"
                        >添加
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column prop="ctr_dir" label="控制器目录">
            </el-table-column>
            <el-table-column prop="ctr" label="控制器"></el-table-column>
          </el-table>
        </div>
        <div class="boxRight">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="权限名称" prop="access_name">
              <el-input
                v-model="ruleForm.access_name"
                placeholder="请输入权限名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="所属菜单" prop="menuList">
              <el-cascader
                v-model="ruleForm.menuList"
                :options="menuList"
                :props="{
                  label: 'menu_name',
                  value: 'menu_id'
                }"
                clearable
              >
              </el-cascader>
            </el-form-item>
            <el-form-item label="排序">
              <el-input v-model="ruleForm.sort" label="描述文字"></el-input>
            </el-form-item>
            <p class="mb-2 ml-2 text-red-300">升序排列: 页面类权限建议0, 其他权限建议30000, 不填默认30000</p>
            <div class="rightPart">
              <div class="right_title">已添加的路由</div>
              <div class="rightArr w-full ml-4">
                <div
                  class="mb-4 w-full flex justify-between h-100"
                  v-for="(item, index) in createArr"
                  :key="index"
                >
                  {{ item }}
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleRemove(index)"
                    class="btnDel">
                    移除
                  </el-button>
                </div>
              </div>
            </div>
          </el-form>
          <span slot="footer" class="bottomPart">
            <el-button @click="handleClose">返回</el-button>
            <el-button type="primary" @click="handleConfirm('ruleForm')">确认</el-button>
          </span>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script>
import letterSearch from "../permissionList/childComps/letterSearch.vue";
import {
  allctr,
  allMenuList,
  addAccess,
  editAccess
} from "@/api/routingList/routingList";

export default {
  name: "editModal",
  components: {
    letterSearch
  },
  data() {
    return {
      zmValue: "A",
      status: "add",
      currentId: "",
      tableData: [],
      menuList: [],
      //已添加的路由
      createArr: [],
      createdId: [],
      ruleForm: {
        menuList: [],
        sort: null,
        access_name: undefined,
        menu_id: undefined,
        route_ids: undefined
      },
      competence: {},
      rules: {
        access_name: [
          { required: true, message: "请输入权限名称", trigger: "blur" }
        ],
        menuList: [{ required: true, message: "请选择菜单", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
    this.status = this.$route.query.status;
    if (this.status == "edit") {
      this.competence = JSON.parse(window["localStorage"].getItem("row"));
      console.log(this.competence);
      this.ruleForm.id = this.competence.id;
      this.ruleForm.access_name = this.competence.name;
      this.ruleForm.sort = this.competence.sort
      this.ruleForm.menuList = [
        this.competence.parent_id,
        this.competence.menu_id
      ];
      this.competence.routes.map(item => {
        this.createdId.push(item.route_id);
        this.createArr.push(item.uri + ":" + item.method);
      });
    } else {
      this.competence = JSON.parse(window["localStorage"].getItem("row"));
      this.createdId.push(this.competence.id);
      this.createArr.push(this.competence.uri + ':' + this.competence.method);
    }
    this.getMenuList();
  },
  methods: {
    getList() {
      allctr({ ctr_initials: this.zmValue }).then(res => {
        console.log(res.data, "data");
        this.tableData = res.data;
      });
    },
    async getMenuList() {
      const { data } = await allMenuList();
      this.menuList = data;
    },
    //添加
    handleAdd(row) {
      let temp = `${row.uri}:${row.method}`;
      if (!this.createArr.includes(temp)) {
        this.createdId.push(row.id);
        this.createArr.push(temp);
      } else this.$message.info("该路由已添加");
    },
    //移除
    handleRemove(index) {
      console.log(index);
      this.createArr.splice(index, 1);
      this.createdId.splice(index, 1);
    },
    //返回
    handleClose() {
      this.$router.go(-1);
    },
    //清空表单
    handleClear() {
      this.ruleForm = {
        menuList: [],
        access_name: undefined,
        menu_id: undefined,
        route_ids: undefined
      };
      this.createArr = [];
      this.createdId = [];
    },
    //确认
    handleConfirm() {
      this.ruleForm.menu_id = this.ruleForm.menuList[ this.ruleForm.menuList.length - 1 ];
      const ids = this.createdId.toString();
      this.ruleForm.route_ids = ids;

      console.log(ids);
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          if (this.status === "add") {
            let data = {
              access_name: this.ruleForm.access_name,
              menu_id: this.ruleForm.menu_id,
              route_ids: this.ruleForm.route_ids,
            };
            if (this.ruleForm.sort || this.ruleForm.sort === 0) data.sort = this.ruleForm.sort

            addAccess(data).then(res => {
              if (res.code === 200) {
                this.$message.success("添加成功");
                this.handleClear();
              } else {}
            });
          }
          if (this.status === "edit") {
            let data1 = {
              id: this.ruleForm.id,
              access_name: this.ruleForm.access_name,
              menu_id: this.ruleForm.menu_id,
              route_ids: this.ruleForm.route_ids
            };

            if (this.ruleForm.sort || this.ruleForm.sort === 0) data1.sort = this.ruleForm.sort

            editAccess(data1).then(res => {
              if (res.code === 200) {
                this.$message.success("编辑成功");
                this.handleClear();
              }
            });
          }
        } else {
          return false;
        }
      });
      // let res = this.status === "add" ? addAccess({}) : editPost({});
    }
  }
};
</script>
<style scoped>
.boxCard {
  width: calc(100% - 40px);
  margin: 20px;
}

.Title {
  font-size: 24px;
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
}

.box {
  display: flex;
  flex-direction: row;
}

.boxLeft {
  width: 55vw;
  margin-top: 10px;
}

.boxRight {
  margin-top: 10px;
  margin-left: 20px;
  width: 30vw;
}

.rightPart {
  display: flex;
  flex-direction: row;
  height: 400px;
  overflow: auto;
}

.right_title {
  white-space: nowrap;
  margin-left: 5px;
  margin-bottom: 20px;
  font-weight: bold;
  color: rgba(96, 98, 102);
}

.rightArr {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.bottomPart {
  width: 250px;
  float: right;
}
</style>
